package vrc

import (
	"bytes"
	"encoding/json"
	"errors"
	"github.com/tidwall/gjson"
	"io/ioutil"
	"net/http"
	"net/url"
	"vrcm/src/vrcm/app/admin/models"
	dto "vrcm/src/vrcm/app/admin/service/dto/vrc"
	"vrcm/src/vrcm/common/service"
	ext "vrcm/src/vrcm/envconfig"
)

var client = http.Client{}

type VrcService struct {
	service.Service
}

// SaveRoom 创建或者编辑合屏房间
func (e *VrcService) SaveRoom(d *dto.SaveRoomReq) (*dto.SaveRoomRes, error) {

	res := &dto.SaveRoomRes{}
	urlPath := ext.ExtConfig.ServiceConfig.VrcServiceUrl + "/rms/v1/room"
	// 参数
	data := make(map[string]interface{})
	data["title"] = d.Title
	data["template"] = d.Template
	data["input_source"] = d.InputSources
	data["poster"] = d.Poster
	data["tenant_id"] = d.TenantId
	data["service_type"] = d.ServiceType
	data["room_type"] = d.RoomType
	data["event_id"] = d.EventId
	data["id"] = d.Id
	data["start_time"] = d.StartTime
	data["activeType"] = "1"
	data["max_user_num"] = d.MaxUserNum
	data["host_user_id"] = d.HostUserId
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return res, err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return res, err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return res, err
	}
	e.Log.Trace("SaveRoom:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return res, errors.New(result.Get("message").String())
	}

	err = json.Unmarshal([]byte(result.Get("data").String()), &res)
	if err != nil {
		e.Log.Errorf("反序列化失败:%s", err)
		return res, err
	}
	return res, nil
}

// SaveRoom1 创建或者编辑合屏房间
func (e *VrcService) SaveRoom1(d *dto.SaveRoomReq) (*dto.SaveRoomRes1, error) {

	res := &dto.SaveRoomRes1{}
	urlPath := ext.ExtConfig.ServiceConfig.VrcServiceUrl + "/mediaRoom/v2/room"
	// 参数
	data := make(map[string]interface{})
	data["title"] = d.Title
	data["media_type"] = "VideoRoom"
	data["merge_engine"] = "vs"
	data["open_status"] = "1"
	data["tenant_id"] = d.TenantId
	data["service_type"] = d.ServiceType
	data["room_type"] = d.RoomType
	data["kickout_mode"] = "reject"
	data["share_mode"] = "open"
	data["start_time"] = d.StartTime
	data["activeType"] = "1"
	data["max_user_num"] = d.MaxUserNum
	data["host_user_id"] = d.HostUserId
	data["room_type"] = "1"
	data["room_mode"] = "public"
	//data["mode"] = "config"
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return res, err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return res, err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return res, err
	}
	e.Log.Trace("SaveRoom:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return res, errors.New(result.Get("message").String())
	}

	err = json.Unmarshal([]byte(result.Get("data").String()), &res)
	if err != nil {
		e.Log.Errorf("反序列化失败:%s", err)
		return res, err
	}
	return res, nil
}

// StartRoom 启动房间
func (e *VrcService) StartRoom(d *dto.StartRoomReq) error {

	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.VrcServiceUrl + "/rms/v1/room/"
	urlString = urlString + d.EventId + "/apply"
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	params.Set("tenant_id", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	e.Log.Trace("StartRoom:", urlPath)
	// 获取 request请求
	request, err := http.NewRequest("GET", urlPath, nil)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return nil
	}
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("StartRoom:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}
	return nil
}

// StopRoom 释放房间
func (e *VrcService) StopRoom(d *dto.StopRoomReq) error {

	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.VrcServiceUrl + "/rms/v1/room/"
	urlString = urlString + d.EventId
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	params.Set("tenant_id", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	e.Log.Trace("StopRoom:", urlPath)
	// 获取 request请求
	request, err := http.NewRequest("DELETE", urlPath, nil)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return nil
	}
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("StopRoom:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK && result.Get("code").Int() != 5006 {
		return errors.New(result.Get("message").String())
	}
	return nil
}

// DeleteRoom 删除房间
func (e *VrcService) DeleteRoom(d *dto.DeleteRoomReq) error {

	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.VrcServiceUrl + "/rms/v1/room/"
	urlString = urlString + d.EventId + "/delete"
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	params.Set("tenant_id", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	e.Log.Trace("DeleteRoom:", urlPath)
	// 获取 request请求
	request, err := http.NewRequest("DELETE", urlPath, nil)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return nil
	}
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("DeleteRoom:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK && result.Get("code").Int() != 5006 && result.Get("code").Int() != 1004 {
		return errors.New(result.Get("message").String())
	}
	return nil
}

// DeleteRoom1 删除房间
func (e *VrcService) DeleteRoom1(d *dto.DeleteRoomReq) error {

	err := e.StopRoom(&dto.StopRoomReq{TenantId: d.TenantId, EventId: d.EventId})
	if err != nil {
		e.Log.Errorf("StopRoom error:%s", err)
		return err
	}

	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.VrcServiceUrl + "/mediaRoom/v2/room/delete/"
	urlString = urlString + d.EventId
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	params.Set("tenant_id", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	e.Log.Trace("DeleteRoom:", urlPath)
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, nil)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return nil
	}
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("DeleteRoom:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK && result.Get("code").Int() != 5006 && result.Get("code").Int() != 1004 {
		return errors.New(result.Get("message").String())
	}
	return nil
}

// RestartRoom 重启房间
func (e *VrcService) RestartRoom(d *dto.StartRoomReq) error {
	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.VrcServiceUrl + "/rms/v1/room/"
	urlString = urlString + d.EventId + "/restartMcu"
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	params.Set("tenant_id", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	e.Log.Trace("RestartRoom:", urlPath)
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, nil)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return nil
	}
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("RestartRoom:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK && result.Get("code").Int() != 5006 && result.Get("code").Int() != 1004 {
		return errors.New(result.Get("message").String())
	}
	return nil
}
